package lukeer.fencing;

import csproj.fencing.Move;
import csproj.fencing.Player;

import java.util.ArrayList;

/**
 * Player using Java Random class to choose the best move to play.
 *
 * User: Luke Richardson lukeer, Wafa M'Barek wmbarek
 * Date: 15/09/12
 * Time: 20:32
 */
public class RandomPlayer extends BasicPlayer implements Player, csproj.fencing.Piece {
    /**
     * Generates a random move and places the move on the currentGameState board.
     *
     * @return move to be tested by opponent
     */
    public Move makeMove() {
        Move m = generateRandomMove();
        try {
            currentGameState.placePiece(m);
        } catch (FencingException e) {
            System.err.println("Illegal move generated by Random player");
            System.exit(1);
        }
        return m;
    }

    /**
     * Generates random moves, checks against arrays which keep track of board state.
     *
     * @return random move
     */
    private Move generateRandomMove() {
        Pair piece = null, fence = null;
        boolean hasFence = true;
        int direction = r.nextInt(2) + 1;

        if (!currentGameState.isFull()) {
            piece = generatePiece();
            hasFence = r.nextBoolean();
        }

        if (direction == HORIZONTAL) fence = generateHFence();
        if (direction == VERTICAL) fence = generateVFence();


        if (currentGameState.isFull())
            return new Move(-1, -1, player, false, fence.getX(), fence.getY(), true, direction);
        if (hasFence)
            return new Move(piece.getX(), piece.getY(), player, true, fence.getX(), fence.getY(), true, direction);
        return new Move(piece.getX(), piece.getY(), player, true, -1, -1, false, 0);
    }

    /**
     * Returns the position of a legal piece placement on the currentGameState board
     *
     * @return position of place on board
     */
    private Pair generatePiece() {
        ArrayList<Pair> pieces = currentGameState.getEmptyPositions();
        return pieces.get(r.nextInt(pieces.size()));
    }

    /**
     * Returns the position of a legal horizontal fence placement on the currentGameState board
     *
     * @return position of horizontal fence on board
     */
    private Pair generateHFence() {
        ArrayList<Pair> hFences = currentGameState.getEmptyHFences();
        return hFences.get(r.nextInt(hFences.size()));
    }

    /**
     * Returns the position of a legal vertical fence placement on the currentGameState board
     *
     * @return position of vertical fence on board
     */
    private Pair generateVFence() {
        ArrayList<Pair> vFences = currentGameState.getEmptyVFences();
        return vFences.get(r.nextInt(vFences.size()));
    }
}
